<?php
/* SVN FILE: $Id: assessments_controller.php 40 2009-12-24 14:45:29Z kenreily@gmail.com $ */
/**
 * Short description for file.
 *
 * Long description for file
 *
 * PHP versions 4 and 5
 *
 * Recenseo: Online submission and reviewing for education
 * Copyright 2008-2009, Ken Reily
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * $Date: 2009-12-24 14:45:29 +0000 (Thu, 24 Dec 2009) $
 * $Revision: 40 $
 * $Author: kenreily@gmail.com $
 * $HeadURL: http://recenseo.googlecode.com/svn/trunk/app/controllers/assessments_controller.php $
 */
class AssessmentsController extends AppController
{
  var $name = 'Assessments';
  var $helpers = array('Time');
  var $components = array('Email');
  var $uses = array('Assessment',
		    'AssignedAssessment',
		    'Assignment',
		    'Submission',
		    'AssessmentTestCase',
		    'AssessmentQualityAttribute',
		    'AssessmentRating');

  function add($submission_id)
  {
    $user_id = $this->Session->read('Auth.User.id');

    // First, be sure this user has been assigned to this submission.
    $asmt_assignments = 
      $this->AssignedAssessment->getForSubmission($submission_id,
						  $user_id);

    if (count($asmt_assignments) > 0) 
    {
      $asmt = $this->Assessment->getForSubmission($submission_id,	
						  $user_id);

      // There is already an assessment. Don't create a new one!
      if (count($asmt) > 0) 
      {
	$assessment_id = $asmt[0]['Assessment']['id'];
      } 
      else 
      {
	$data['Assessment']['submission_id'] = $submission_id;
	$data['Assessment']['user_id'] = $user_id;

	$params = array('conditions' => array('Assignment.id' => $asmt_assignments[0]['Assignment']['id']),
			'contain' => array('QualityAttribute'));
	$assignment = $this->Assignment->find('first',$params);
	
	foreach ($assignment['QualityAttribute'] as $quality_attribute) {
	  $data['AssessmentQualityAttribute'][]['quality_attribute_id'] = 
	    $quality_attribute['id'];
	}
	
	$this->Assessment->saveAll($data,array('atomic' => true));
	$assessment_id = $this->Assessment->id;
      }

      $this->redirect("/assessments/edit/{$assessment_id}");
      
    } else {
      $this->flash('You are not assigned to this submission.',"/assessments/index/{$asmt_assignments[0]['Course']['id']}");
    }

  }
  
  function index($course_id)
  {
    $courseinfo = 
      $this->Assessment->Submission->Assignment->Course->findById($course_id);
    $this->pageTitle = "Assessments for {$courseinfo['Course']['name']}";

    $assessments = 
      $this->Assessment->getForCourse($courseinfo['Course']['id'],
				      $this->Session->read('Auth.User.id'));
    $this->set("assessments",$assessments);

    $assessment_assignments = 
      $this->AssignedAssessment->getForCourse($courseinfo['Course']['id'],
					      $this->Session->read('Auth.User.id'));
    $this->set("assessmentAssignments",$assessment_assignments);

  }

  function rate($id = null)
  {
    if (!empty($this->data))
    {
      $this->data['Assessment']['ratings_submitted'] = date('Y-m-d H:i:s');

      if ($this->Assessment->save($this->data))
      {
	$this->redirect("/submissions/view/{$this->data['Submission']['id']}");
      }
    }

    $this->data = $this->Assessment->getForRating($id,$this->Session->read('Auth.User.id'));

    if (empty($this->data))
    {
      $this->Session->setFlash('Assessment not found.');
    } 
    else 
    {
      $this->pageTitle = "Rate Asessment of Your Submission #{$this->data['Submission']['id']}";
      
      if (empty($this->data['Assessment']['author_rating'])) 
      {
	$this->set("test_cases",$this->Assessment->AssessmentTestCase->getForAssessment($id));
	$this->set("qualities",$this->Assessment->AssessmentQualityAttribute->getForAssessment($id));
      } 
      else 
      {
	$this->redirect("/assessments/view/{$id}");
      }
    }
  }

  function edit($id = null)
  {
    if (!empty($this->data))
    {
      $this->data['Assessment']['submitted'] = date('Y-m-d H:i:s');
      
      if ($this->Assessment->save($this->data))
      {
	$assessment = $this->Assessment->findById($id);
	$assignment = $this->Assignment->findById($assessment['Submission']['assignment_id']);

	$this->redirect("/assessments/index/{$assignment['Course']['id']}");
      }
      
    }
    
    $this->data = $this->Assessment->getForEdit($id,$this->Session->read('Auth.User.id'));

    if (empty($this->data)) 
    {
      $this->Session->setFlash('Assessment not found.');
    } 
    else 
    {
      $this->pageTitle = "Edit Your Assessment of Submission #{$this->data['Submission']['id']}";
      
      // If the assessment has been submitted, then redirect the user to the view.
      // Otherwise, load up the test cases and code qualities for display.
      if (empty($this->data['Assessment']['submitted'])) 
      {
	$this->set("test_cases",$this->Assessment->AssessmentTestCase->getForAssessment($id));
	$this->set("qualities",$this->Assessment->AssessmentQualityAttribute->getForAssessment($id));
      } 
      else 
      {
	$this->redirect("/assessments/view/{$id}");
      }
    }
  }
  
  function view($id)
  {
    $user = $this->Session->read('Auth.User');

    $params = array('conditions' => array('Assessment.id' => $id),
		    'recursive' => 0,
		    'fields' => array('Assessment.*',
				      'Submission.id',
				      'Submission.user_id'));
    $assessment = $this->Assessment->find('first',$params);
    
    if (empty($assessment))
    {
      $this->Session->setFlash('Assessment not found.');
    }
    else if ($assessment['Assessment']['user_id'] != $user['id'] &&
	     $assessment['Submission']['user_id'] != $user['id'] &&
	     $user['role'] != 'Instructor')
    {
      $this->Session->setFlash('You are not authorized to view this assessment.');
    }
    else if (empty($assessment['Assessment']['submitted']))
    {
      $this->Session->setFlash = ('This assessment is still in progress.');
    }
    else
    {
      $this->set('assessment',$assessment);
      $this->pageTitle = "View Assessment of Submission #{$assessment['Submission']['id']}";

      $params = 
	array('conditions' => array('Submission.id' => $assessment['Submission']['id']),
	      'recursive' => 0,
	      'fields' => array('Submission.id',
				'Submission.user_id',
				'Submission.comments',
				'Submission.file_name',
				'Submission.file_type',
				'Submission.file_size',
				'Assignment.*',
				'GradingOption.*'));
      $submission = $this->Submission->find('first',$params);
      $this->set('submission',$submission);

      $test_cases = $this->AssessmentTestCase->findAllByAssessmentId($id);
      $this->set("test_cases",$test_cases);

      $qualities = $this->AssessmentQualityAttribute->findAllByAssessmentId($id);
      $this->set("qualities",$qualities);

      $ratings = $this->AssessmentRating->findAllByAssessmentId($id);
      $this->set('ratings',$ratings);
    }
  }
   
  function submit_ratings($id)
  {
    $conds = array('Assessment.id' => $id);
    
    $fields = array('Submission.id',
      'Assessment.submitted',
      'Assessment.ratings_submitted',
      'Assessment.user_id');

    $ratings = $this->Assessment->find('first',array(
        'conditions' => $conds,
        'fields' => $fields));
    
    if (empty($ratings['Assessment']['submitted']))
    {
      $this->flash('This assessment has not been submitted!',"/assessments/view/{$id}");
    }
    else if (!empty($ratings['Assessment']['ratings_submitted']))
    {
      $this->flash('Your ratings have already been submitted.',"/assessments/view/{$id}");
    }
    else
    {
      // Validation checks pass, go ahead and submit the ratings.
      $this->Assessment->id = $id;

      if ($this->Assessment->saveField('ratings_submitted',date('Y-m-d H:i:s')))
      {
        $user_id = $ratings['Assessment']['user_id'];
        $user = $this->Assessment->User->findById($user_id);
        $this->set('assessment_id',$id);
        
        // TODO: Move email address to user table.
        $this->Email->to = $user['User']['username'] . '@umn.edu';
        $this->Email->subject = 'Your assessment has been reviewed by the submission author';
        $this->Email->from = 'Ken Reily <reil0037@umn.edu>';
        $this->Email->bcc = array('Ken Reily <reil0037@umn.edu>');
        $this->Email->template = 'assessment_rating_complete';
        $this->Email->sendAs = 'text';
        $this->Email->send();          

        $this->flash('Your ratings have been submitted to the reviewer.',"/assessments/view/{$id}");
      }
      else
      {
        $this->flash('There was an error submitting your ratings.',"/assessments/view/{$id}");
      }
    }
  }
}
?>